package com.us.usws.support.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import net.iwsh.core.common.Wildcard;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.servlet.GuiceFilter;

public class GuiceCustomerFilter extends GuiceFilter {

	private static Log log = LogFactory.getLog(GuiceCustomerFilter.class);

	private String handleExp = "";

	protected FilterConfig filterConfig;

	/**
	 * main logic
	 */
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
			ServletException {

		HttpServletRequest req = (HttpServletRequest) servletRequest;
		//HttpServletResponse resp = (HttpServletResponse) servletResponse;

		//firstly set UTF-8 charset
		servletRequest.setCharacterEncoding("UTF-8");
		servletResponse.setCharacterEncoding("UTf-8");

		//get request path
		String path = req.getRequestURI();

		//if it's ajax request
		if (path.contains("ajax")) {
			servletResponse.setContentType("application/json; charset=UTF-8");
		} else if (path.endsWith(".mp4")) {
			servletResponse.setContentType("video/mp4");
		} else if (path.endsWith(".3gp")) {
			servletResponse.setContentType("video/3gpp");
		}

		//check whether the url should be ignored.
		if (!shouldHandle(path)) {
			log.debug("{GuiceCustomFilter} :: Ignore URL: [" + path + "].");
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		//call super class's filter
		super.doFilter(servletRequest, servletResponse, filterChain);
	}

	/**
	 * whether should ignore the url
	 * @param str
	 * @return
	 */
	private boolean shouldHandle(String str) {
		if (handleExp == null) {
			return true;
		}
		boolean matches = Wildcard.matchesIgnoreCase(handleExp, str, ",");
		log.info("handleExp=[" + handleExp + "], path=[" + str + "], matches=[" + matches + "]");
		return matches;
	}

	/**
	 * Take this filter out of service.
	 */
	public void destroy() {
		this.filterConfig = null;
	}

	/**
	* Place this filter into service.
	*
	* @param filterConfig The filter configuration object
	*/
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.handleExp = filterConfig.getInitParameter("handleExp");
	}

}
